import configs from '@/config/app.js'
const LOG_DEBUG =configs.SERVER_DEBUG;
import { chatApi } from "@/api";
import { userApi } from "@/api/user.js";
import store from '@/store'
export default new class {
	constructor() {
		this.handlers = {};
		this.queue = [];
		this.status = false;
		this.timer = null;
        this.timer1 = null;
        this.timer2 =null;
	}
	connect() {
		let url=configs.VUE_APP_WS_URL;
		uni.connectSocket({
			url,
            fail: () => {
               this.status=false;
                if(this.timer1!=null)clearInterval(this.timer1)
                 this.timer1=setInterval(()=>{
                 	if(!this.status) {
						this.connect();
              	     }
           
              }, 3* 1000);
              
            },
		});
        if(this.timer!=null)clearInterval(this.timer)
		this.timer = setInterval(()=>{
			if(!this.status) {
				
				this.connect();
              
                LOG_DEBUG && console.log('[socket] reconnect');
			}
        
		}, 5 * 1000);
		uni.onSocketOpen(() => {
			this.status = true;
			while (this.queue.length) this.send(this.queue.pop());
			LOG_DEBUG && console.log('[socket] init');
			clearInterval(this.timer2)
			this.timer2=setInterval(()=>{
               	if(this.status) {
					 this.send({
						type: 'ping'
					 });
				}
                       
            }, configs.PINGINTERVAL);
			this.emit('init');
			// console.log('初始化成功')
		});
		uni.onSocketError(() => {
			this.status = false;
			LOG_DEBUG && console.log('[socket] error');
			this.emit('error');
		});
		uni.onSocketMessage((res) => {
			console.log(res)
			
			let result = JSON.parse(res.data);
			if (result) {
				if(result.code!=200){
					console.error(result)
					return false;
				}
				LOG_DEBUG && console.log('[socket] recevice : ', result);
				switch (result.type) {
					case 'init':
						if(store.getters.isLogin){							
							this.send({
								type:'bind',
								os:store.getters.systeminfo
							});   
						}
					break;
					case 'ping':
						this.send({
							type:'pong',
						});
					break;
					case 'config':
						store.commit("SETCONFIG",result.data);
					break;
					case 'userInfo':
						store.commit("UPDATE_USERINFO",result.data);
						
					break;
					default:
						this.emit(result.type, result);
					break;
				}
			}
		});
		uni.onSocketClose(() => {
			this.status = false;
			LOG_DEBUG && console.log('[socket] close');
			this.emit('close');
		});
	}
	send(data) {
		return new Promise((reslove, reject) => {			
			if (this.status) {
				data.token=store.getters.token??"";
				data.uid=store.getters.token?store.getters.uid??"":"";
				data.formType=configs.HEADER['Form-type'];
				LOG_DEBUG && console.log('[socket] send', data);
				uni.sendSocketMessage({
					data: typeof(data) == 'string' ? data : JSON.stringify(data),
					success: (res) => {
						reslove({message:"ok",res:res,data:data})
					},
					fail: (error) => {
					  this.status = false;
					  this.connect();
					  this.queue.push(data);
					  reject({message:"error",msg:"发送到服务器失败,重新连接中...",data:{error:error,data:data}})
					},
					
				});
			} else {
				this.queue.push(data);
				this.connect();
				reject({message:"error",msg:"连接状态丢失,重新连接中...",data:{status:this.status,data:data}})
			}
		})
	}
	on(eventType, handler) {
		var self = this;
		if (!(eventType in self.handlers)) {
			self.handlers[eventType] = [];
		}
		self.handlers[eventType].push(handler);
		return this;
	}
	emit(eventType) {
		var self = this;
		var handlerArgs = Array.prototype.slice.call(arguments, 1);
		if (!self.handlers[eventType]) return self;
		for (var i = 0; i < self.handlers[eventType].length; i++) {
			self.handlers[eventType][i].apply(self, handlerArgs);
		}
		return self;
	}
	off(eventType, handler) {
		var currentEvent = this.handlers[eventType];
		var len = 0;
		if (currentEvent) {
			len = currentEvent.length;
			for (var i = len - 1; i >= 0; i--) {
				if (currentEvent[i] === handler) {
					currentEvent.splice(i, 1);
				}
			}
		}
		return this;
	}
};
